<template>
  <div class="video-container">
    <canvas ref="canvasPlayer" style="width: 100%; height: 100%;"></canvas>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'

const canvasPlayer = ref(null)
const canvasContext = ref(null)
let ws = null
let animationFrameId = null
let reconnectTimeout = null
let reconnectAttempts = 0
const maxReconnectAttempts = 5
const reconnectInterval = 3000

 onMounted(() => {
   console.log('VideoStream组件已挂载')
   initCanvas()
   connectWebSocket()
 })

onUnmounted(() => {
  console.log('VideoStream组件已卸载')
  if (ws) {
    ws.close()
  }
  if (animationFrameId) {
    cancelAnimationFrame(animationFrameId)
  }
  if (reconnectTimeout) {
    clearTimeout(reconnectTimeout)
  }
})

const initCanvas = () => {
  if (canvasPlayer.value) {
    canvasContext.value = canvasPlayer.value.getContext('2d')
  }
}

const connectWebSocket = () => {
  // 使用正确的代理地址连接WebSocket
  const wsUrl = import.meta.env.VITE_WEBSOCKET_URL || 'ws://key-nice-falcon.ngrok-free.app/video'
  console.log('尝试连接WebSocket:', wsUrl)
  
  try {
    ws = new WebSocket(wsUrl)
    ws.binaryType = 'arraybuffer'
    
    ws.onopen = () => {
      console.log('WebSocket连接已建立')
      ElMessage.success('WebSocket连接已建立')
      reconnectAttempts = 0 // 重置重连次数
    }
    
    ws.onmessage = (event) => {
      console.log('收到WebSocket消息，类型:', typeof event.data)
      if (event.data instanceof ArrayBuffer) {
        console.log('收到二进制数据，大小:', event.data.byteLength)
        handleBinaryData(event.data)
      } else {
        console.log('收到文本消息:', event.data)
        ElMessage.success(event.data)
      }
    }
    
    ws.onerror = (error) => {
      console.error('WebSocket错误:', error)
      ElMessage.error('WebSocket错误: ' + error.message)
    }
    
    ws.onclose = () => {
      console.log('WebSocket连接已关闭')
      ElMessage.error('WebSocket连接已关闭')
      // 尝试重连
      if (reconnectAttempts < maxReconnectAttempts) {
        reconnectAttempts++
        console.log(`尝试重连 (${reconnectAttempts}/${maxReconnectAttempts})...`)
        reconnectTimeout = setTimeout(() => {
          connectWebSocket()
        }, reconnectInterval)
      } else {
        ElMessage.error('WebSocket连接失败，已达到最大重连次数')
      }
    }
  } catch (error) {
    console.error('创建WebSocket连接时出错:', error)
    ElMessage.error('创建WebSocket连接时出错: ' + error.message)
  }
}

const handleBinaryData = (data) => {
  const buffer = new Uint8Array(data)
  
  // 检查数据长度
  if (buffer.length < 5) {
    console.warn('收到的数据太短:', buffer.length)
    return
  }
  
  // 解析消息类型 (1字节)
  const messageType = buffer[0]
  
  // 解析payload长度 (4字节, 大端序)
  const payloadLength = new DataView(data).getUint32(1, false) // false表示大端序
  
  // 检查数据完整性
  if (buffer.length < 5 + payloadLength) {
    console.warn('数据不完整，期望长度:', 5 + payloadLength, '实际长度:', buffer.length)
    return
  }
  
  // 如果是图像帧 (0x01)
  if (messageType === 0x01) {
    // 提取JPEG图像数据
    const imageData = buffer.slice(5, 5 + payloadLength)
    
    // 显示图像
    displayImage(imageData)
  } else {
    console.log('未知的消息类型:', messageType)
  }
}

const displayImage = (imageData) => {
  const blob = new Blob([imageData], { type: 'image/jpeg' })
  const url = URL.createObjectURL(blob)
  
  const img = new Image()
  img.onload = () => {
    if (canvasContext.value && canvasPlayer.value) {
      canvasPlayer.value.width = img.width
      canvasPlayer.value.height = img.height
      canvasContext.value.drawImage(img, 0, 0)
    }
    URL.revokeObjectURL(url)
  }
  
  img.onerror = () => {
    console.error('图像加载失败')
    URL.revokeObjectURL(url)
  }
  
  img.src = url
}
</script>

<style scoped>
.video-container {
  width: 100%;
  height: 100%;
}
</style>